import csv
import json
import requests
import unittest
import setup_common

class AsnTest(unittest.TestCase):
    def setUp(self):
        self.ip = setup_common.get_shared_ip()
        self.storedurl = setup_common.generate_url(self.ip, "asn/sorted")
        self.asndetailurl = setup_common.generate_url(self.ip,"asn/detail")
        self.headers = setup_common.get_shared_headers()
        # 用于跟踪已经处理的 ASN 编码
        self.processed_asn_codes = set()
        self.csv_filename = "asn_list.csv"

    def read_csv_file(self, csv_filename):
        data_list = []
        with open(csv_filename, mode='r', newline='', encoding='utf-8') as file:
            fieldnames = ['id', 'asn_code', 'asn_status', 'supplier']
            reader = csv.DictReader(file, fieldnames=fieldnames)
            next(reader)  # Skip the header row
            for row in reader:
                # 检查 asn_status 是否等于 3
                if row["asn_status"] == "3":
                    data_list.append(row)
        return data_list

    def get_asn_detail(self, asn_code):
        data_list = self.read_csv_file("asn_list.csv")
        goods_list = []
        for item in data_list:
            asn_code = item["asn_code"]
            asn_status = item["asn_status"]
            asn_detail_url = f"{self.asndetailurl}?asn_code={asn_code}"
            print("4,", asn_detail_url)
            try:
                response = requests.get(url=asn_detail_url, headers=self.headers, timeout=10)
                response_text = response.text
                if response.status_code >= 200 and response.status_code < 300:
                    data = json.loads(response_text)
                    for goods_item in data["results"]:
                        goods_list.append({
                            "id": goods_item["id"],
                            "asn_code": goods_item["asn_code"],
                            "goods_code": goods_item["goods_code"],
                            "goods_qty": goods_item["goods_qty"],
                            "goods_actual_qty": goods_item["goods_qty"]
                        })
                else:
                    print(f"HTTP error: {response.status_code} - {response_text}")
            except requests.exceptions.RequestException as e:
                print(f"Error in request: {e}")
        return goods_list

    def post_asn_stored(self, data_list, goods_list):
        payout_list = []  # 用于存储最终的 payout 数据
        supplier_list = []  # 初始化 supplier_list
        # 构建一个字典用于存储不同 asn_code 对应的 goodsData 列表
        asn_goods_data_dict = {}
        for item, goods_item in zip(data_list, goods_list):
            asn_code = goods_item["asn_code"]
            if asn_code not in asn_goods_data_dict:
                asn_goods_data_dict[asn_code] = []

            supplier = item["supplier"]
            supplier_list.append(supplier)  # 将 supplier 存储到列表中
            goods_data = {
                "id": goods_item["id"],
                "asn_code": goods_item["asn_code"],
                "supplier": supplier,
                "goods_code": goods_item["goods_code"],
                "goods_qty": goods_item["goods_actual_qty"],
                "goods_actual_qty": str(goods_item["goods_actual_qty"])
            }
            asn_goods_data_dict[asn_code].append(goods_data)

        # 构造最终的 payout 数据
        for j, (asn_code, goods_data_list) in enumerate(asn_goods_data_dict.items()):
            #supplier = data_list[j]["supplier"]
            supplier = supplier_list[j]  # 使用存储的 supplier
            payout = {
                "asn_code": asn_code,
                "supplier": supplier,
                "goodsData": goods_data_list,
                "creater": "cow11023"
            }
            payout_list.append(payout)

        # 构造asn_stored_url和payout_item
        for goods_item, payout_item in zip(data_list, payout_list):
            id_value = goods_item["id"]
            asn_stored_url = f"{self.storedurl}{id_value}/"
            print(5, asn_stored_url)

            # 打印当前迭代的payout_item
            print("6,具体的提交数据: ", json.dumps(payout_item, indent=4))

            # 发送POST请求并处理响应
            # 构造asn_stored_urls列表，包含多个ASN记录的URL
            asn_stored_urls = [f"{self.storedurl}{item['id']}/" for item in data_list]
            for asn_stored_url, payout_item in zip(asn_stored_urls, payout_list):
                print(5, asn_stored_url)

                # 打印当前迭代的payout_item
                print("6,具体的提交数据: ", json.dumps(payout_item, indent=4))

                # 发送POST请求并处理响应
                response = requests.post(url=asn_stored_url, headers=self.headers, json=payout_item).text
                print(response)

                self.processed_asn_codes.add(payout_item["asn_code"])
                print(self.processed_asn_codes)

        # 在 post 操作完成后，更新 CSV 文件中已执行过 POST 操作的 ASN 记录的 asn_status 字段
        updated_data_list = data_list.copy()  # 创建一个副本以避免修改原始数据
        for item in updated_data_list:
            asn_code = item["asn_code"]
            if asn_code in self.processed_asn_codes:
                # 假设你想将 asn_status 值加1
                item["asn_status"] = str(int(item["asn_status"]) + 1)

        # 将更新后的数据写回 CSV 文件
        with open(self.csv_filename, mode='w', newline='', encoding='utf-8') as file:
            fieldnames = ['id', 'asn_code', 'asn_status', 'supplier']
            writer = csv.DictWriter(file, fieldnames=fieldnames)
            writer.writeheader()  # 写入表头
            for item in updated_data_list:
                writer.writerow(item)

    def test_asn_stored(self):
        csv_filename = "asn_list.csv"
        data_list = self.read_csv_file(csv_filename)
        id_list = [item["id"] for item in data_list]
        goods_list = self.get_asn_detail(id_list)
        self.post_asn_stored(data_list, goods_list)

if __name__ == '__main__':
    unittest.main()